package com.CTAtracker.android.api;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

import com.CTAtracker.android.Adapters.FavoriteStopAdapter;
import com.CTAtracker.android.Adapters.StopItemAdapter;
import com.CTAtracker.android.Widget.FavoriteRemoteViewFactory;
import com.CTAtracker.android.XML.APIXmlParser;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * The class that deals with the response of the call of the API
 */
public class XMLResponseHandler extends AsyncHttpResponseHandler{
	/**
	 * The XML parser 
	 */
	private APIXmlParser _apiXmlParser;
	/**
	 * Log
	 */
	private static final String TAG = "XMLResponseHandler";
	
	/**
	 * Constructor, instantiate the XML parser
	 * @param stopItemAdapter
	 */
	public XMLResponseHandler(StopItemAdapter stopItemAdapter){
		super();
		_apiXmlParser = new APIXmlParser();
		_apiXmlParser.addObserver(stopItemAdapter);
	}
	
	public XMLResponseHandler(FavoriteStopAdapter favoriteStopAdapter) {
		super();
		_apiXmlParser = new APIXmlParser();
		_apiXmlParser.addObserver(favoriteStopAdapter);
	}

	public XMLResponseHandler(FavoriteRemoteViewFactory favoriteRemoteViewFactory) {
		super();
		_apiXmlParser = new APIXmlParser();
		_apiXmlParser.addObserver(favoriteRemoteViewFactory);
	}

	/**
	 * On success call the method parse of _apiXmlParser
	 */
	@Override
    public void onSuccess(String response) {
        try {
			_apiXmlParser.parse(new ByteArrayInputStream(response.getBytes()));
			Log.i(TAG, "Success on retrieving the response");
		} catch (XmlPullParserException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
    }

	@Override
	public void onFailure(Throwable arg0, String arg1) {
		super.onFailure(arg0, arg1);
		Log.e(TAG, "Filure on retrieving the response");
	}
	
	
}
